package com.mainactivity.usbhost;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Iterator;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    //UI
    private TextView usbDescibetextView = null, usbdatatextView = null;
    private EditText senddataedittext = null;
    private Button senddatabutton = null;

    private String mystring = new String();

    private static final String TAG = "mytag";
    UsbManager manager;
    private UsbDevice device = null;
    UsbInterface[] usbinterface = null;
    UsbEndpoint[][] endpoint = new UsbEndpoint[5][5];
    UsbDeviceConnection connection = null;
    byte[] mybuffer = new byte[1024];
    private int myvid = 1155, mypid = 22336;

    DataTransfer mydatatransfer = new DataTransfer(1024);
    ConnectedThread mconnectedthread = null;
    DrawContralThread mdrawcontralthread = null;
    boolean threadcontrol_ct = false;
    boolean threadcontrol_mt = false;
    boolean threadsenddata = false;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {//此方法在ui线程运行

            switch (msg.what) {
                case 1:
                    int datalen = mydatatransfer.GetDataLen();
                    byte[] mtmpbyte = new byte[datalen];

                    mydatatransfer.ReadMultiData(mtmpbyte, datalen);
                    usbdatatextView.setText("buff长度:" + datalen  + ",\n" +ByteUtil.byte2String(mtmpbyte));

                    break;
                case 2:
                  //  usbdatatextView.setText(mystring);
                default:
                    break;
            }
        }
    };

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            finish();
        }

        ;
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        threadcontrol_ct = false;
        threadcontrol_mt = false;
        Toast.makeText(this, "USB设备被拔出,应用退出", Toast.LENGTH_LONG).show();
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UI_Init();
        senddatabutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // TODO Auto-generated method stub
                threadsenddata = true;
                Toast.makeText(MainActivity.this, "数据已经发送", Toast.LENGTH_LONG).show();
            }
        });

        IntentFilter filter = new IntentFilter("android.hardware.usb.action.USB_DEVICE_DETACHED");
        registerReceiver(mUsbReceiver, filter);


        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Log.e(TAG, "get device list  = " + deviceList.size());
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            device = deviceIterator.next();
            Log.i(TAG, "vid: " + device.getVendorId() + "\t pid: " + device.getProductId());
            if (device.getVendorId() == myvid && device.getProductId() == mypid) {
                break;
            }
        }
        if (device != null && device.getVendorId() == myvid && device.getProductId() == mypid) {
            usbDescibetextView.setText("找到设备:" + device.getVendorId() + "\t pid: " + device.getProductId());
        } else {
            usbDescibetextView.setText("未发现支持设备");
            finish();
            return;
        }

        PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        if (manager.hasPermission(device)) {
        } else {
            manager.requestPermission(device, pi);
        }

        if (manager.hasPermission(device)) {
            usbDescibetextView.setText(usbDescibetextView.getText() + "\n拥有访问权限");
        } else {
            usbDescibetextView.setText(usbDescibetextView.getText() + "\n未获得访问权限");
        }

        usbDescibetextView.setText(usbDescibetextView.getText()
                + "\n" + device.getDeviceName());

        usbDescibetextView.setText(usbDescibetextView.getText()
                + "\n接口数为：" + device.getInterfaceCount());

        usbinterface = new UsbInterface[device.getInterfaceCount()];
        for (int i = 0; i < device.getInterfaceCount(); i++) {
            usbinterface[i] = device.getInterface(i);
            usbDescibetextView.setText(usbDescibetextView.getText()
                    + "\n接口" + i + "的端点数为：" + usbinterface[i].getEndpointCount());
            for (int j = 0; j < usbinterface[i].getEndpointCount(); j++) {
                endpoint[i][j] = usbinterface[i].getEndpoint(j);
                if (endpoint[i][j].getDirection() == 0) {
                    usbDescibetextView.setText(usbDescibetextView.getText()
                            + "\n端点" + j + "的数据方向为输出");
                } else {
                    usbDescibetextView.setText(usbDescibetextView.getText()
                            + "\n端点" + j + "的数据方向为输入");
                }
            }
        }

        threadcontrol_ct = true;
        threadcontrol_mt = true;
        if (mconnectedthread != null) {
            mconnectedthread = null;
        }
        mconnectedthread = new ConnectedThread();
        mconnectedthread.start();

        if (mdrawcontralthread != null) {
            mdrawcontralthread = null;
        }

        mdrawcontralthread = new DrawContralThread();
        mdrawcontralthread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void ToastOnUi(final String content) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, content + "", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void UI_Init() {
        usbDescibetextView = (TextView) findViewById(R.id.usbDescribtextView);
        usbdatatextView = (TextView) findViewById(R.id.usbdata);
        senddataedittext = (EditText) findViewById(R.id.senddataeditText);
        senddatabutton = (Button) findViewById(R.id.senddatabutton);
    }

    class ConnectedThread extends Thread {
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
            super.destroy();
        }

        public ConnectedThread() {
            if (connection != null) {
                connection.close();
            }
            connection = manager.openDevice(device);
            connection.claimInterface(usbinterface[1], true);
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            int datalength;
            while (threadcontrol_ct) {
                if (threadsenddata) {
                    threadsenddata = false;
                    final byte[] mytmpbyte = (senddataedittext.getText().toString() + "\r\n").getBytes();
                    ToastOnUi("发送长度:" + mytmpbyte.length);
                    connection.bulkTransfer(endpoint[1][0], mytmpbyte, mytmpbyte.length, 30);
                }
                datalength = connection.bulkTransfer(endpoint[1][1], mybuffer, 1024, 30);
                mydatatransfer.AddData(mybuffer, datalength);
                if (datalength >= 0) {
                    ToastOnUi("收到长度:" + datalength);
                    mHandler.obtainMessage(1).sendToTarget();
                }
            }
        }
    }

    class DrawContralThread extends Thread {
        public DrawContralThread() {

        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (threadcontrol_mt) {
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mHandler.obtainMessage(2).sendToTarget();
            }
        }

    }

}
